02_04 Lifecycle Hooks

Lifecycle Hooks

Sometimes you'll need to take care of things at different points in the life of a Vue application, and to do that, you use LifeCycle hooks.


Events

beforeCreate created beforeMount mounted beforeUpdate updated activated deactivated beforeUnmount unmounted errorCaptured renderTracked renderTriggered

Here's all of the lifecycle events that are available to you. Some of these in blue are available to you during the regular lifecycle of your Vue App and some deal with dynamic components in purple.

So, for example, if you need to do something like load some data after the component has been initialized but not rendered, you could use the created hook in your application.

What you use depends on what you need access to, so although more than one of the methods might work for your needs, you need to be mindful of what's available at each level.


Lifecycle Methods

Here's a visual representation of when most of the hook events take place. This is pretty technical, but Vue does a great job giving you access to just about every useful point in your app's lifecycle.


this context

not this

created: () => this.doSomething()

this

created() { this.doSomething() } 

Here's a couple of things to watch out for.

In lifecycle hooks, the value of this is bound to the hook and that can create a problem with es6's arrow functions, which change the meaning of the this keyword, so although it's tempting, remember to use regular functional syntax.


Where?

  data() { ... },
  created() { ... },
  beforeMount() { ... }

Docsgo.raybo.org/2DJH

Lifecycle hooks are created at the same level of data just like methods and computed properties...the order isn't important, just that it's at the same level.

This is one place where you're going to want to look at the docs to make sure you have what you need from Vue.js.


Practice

  1. Clear out products
  2. Create a lifecycle hook
  3. Use javascript's Fetch APIgo.raybo.org/2DKH
  4. Load from
    https://hplussport.com/api/products/order/price
  5. Try different hooks

bonus: Show cart total and qty on menu

For this project, we're goin to clear out our products array, which manually lists all the products.

We'll create a lifecycle hook in our application

You can use JavaScript's fetch API to load from this URL.

You should try different hooks to see which ones work. Try at least created and keep going down the list until it no longer works.